package com.atguigu.gmall.rabbit.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.autoconfigure.amqp.RabbitTemplateConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.support.RetryTemplate;

/**
 * @Author:lyd
 **/
@Configuration
@Slf4j
public class AppRabbitAutoConfiguration {

    @Bean
    public RabbitTemplate rabbitTemplate(RabbitTemplateConfigurer configurer, ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate();
        configurer.configure(template, connectionFactory);

        //设置confirm 回调
        /**
         * CorrelationData：刚才发送的消息的相关数据
         * ack: 确认状态，代表服务器的exchange是否收到
         * cause： 如果有问题，会打印错误原因
         */
        template.setConfirmCallback((CorrelationData correlationData,
                                     boolean ack,
                                     String cause)->{
            log.info("confirmCallback回调，消息：{}，接收状态：{}，原因：{}",correlationData, ack, cause);
        });

        /**
         * Message message,
         * int replyCode,
         * String replyText,
         * String exchange,
         * String routingKey
         */
        template.setReturnCallback((message,replyCode,replyText,exchange,routingKey)->{
            //消息成功后不会触发，失败才会触发
            log.info("returnCallback回调，消息：{}，响应码：{}，响应文本：{}，交换机：{}，路由键：{}",
                    message,replyCode,replyText,exchange,routingKey);
            //队列接收消息失败后把消息保存到数据库定期重试
        });

        template.setRetryTemplate(new RetryTemplate());
        return template;
    }
}
